//
//  ToponSplashAd.swift
//  ThirdSplashAd
//
//  Created by 张亚浩 on 2023/5/31.
//

import Foundation
import ad_common
import AnyThinkSDK
import AnyThinkSplash
import AppTrackingTransparency


open class ToponSplashAd : ThirdSplashAd, ATSplashDelegate {
    
    private var atSplashAd: ATAPI?
    private var showingAd: Bool?
    private var splashAdLoadStatusListener: ThirdSplashAdStatusListener?
    
    private var appId: String
    private var appKey: String
    
    public override init(appId: String, appKey: String, placementId: String) {
        self.appId = appId
        self.appKey = appKey

        super.init(appId: appId, appKey: appKey, placementId: placementId)
        
        self.initConfig()
    }
    
    public override func initConfig() {
        atSplashAd = ATAPI.sharedInstance()

        if #available(iOS 14, *) {
            ATTrackingManager.requestTrackingAuthorization { (status) in
                do {
                    try ATAPI.sharedInstance().start(withAppID: self.appId, appKey: self.appKey)
                } catch {
                    print("ad splash start failed!")
                }
            }
        } else {
           do {
               try ATAPI.sharedInstance().start(withAppID: self.appId, appKey: self.appKey)
           } catch {
               print("ad splash start failed!")
           }
        }
    }
    
    public override func load() {
        if (atSplashAd == nil) {
            return
        }
        if (ATAdManager.shared().splashReady(forPlacementID: self.placementId)) {
            return
        }
        ATAdManager.shared().loadAD(withPlacementID: self.placementId, extra: [:], delegate: self, containerView: nil)
    }
    
    
    public override func isReady() -> Bool {
        return ATAdManager.shared().splashReady(forPlacementID: self.placementId)
    }
    
    public override func isShowing() -> Bool {
        return self.showingAd ?? false;
    }
    
    public override func setThirdSplashAdStatusListener(listener: ThirdSplashAdStatusListener) {
        self.splashAdLoadStatusListener = listener
    }
    
    public override func show(customSkipView: UIView?) {
        if (!ATAdManager.shared().splashReady(forPlacementID: self.placementId)) {
            return
        }
        ATAdManager.shared().entrySplashScenario(withPlacementID: self.placementId, scene: "")
        
        var extra: Dictionary<AnyHashable, Any> = [
            kATSplashExtraCountdownKey: 500
        ]
        
        if (customSkipView != nil) {
            extra[kATSplashExtraCustomSkipButtonKey] = customSkipView
        }
        
        DispatchQueue.main.async {
            let keyWindow = UIApplication.shared.delegate?.window
            ATAdManager.shared().showSplash(withPlacementID: self.placementId, scene:"", window: keyWindow!, extra: extra, delegate: self)
        }
    }
    
    public func didFinishLoadingAD(withPlacementID placementID: String!) {
    }
    
    public func didFailToLoadAD(withPlacementID placementID: String!, error: Error!) {
        let err = error as NSError
        self.splashAdLoadStatusListener?.onNoAdError(code: String(err.code), desc: err.domain)
    }
    
    public func didFinishLoadingADSource(withPlacementID placementID: String!, extra: [AnyHashable : Any]!) {
        let detailMap = createAdDetailMap(extra: extra)
        self.splashAdLoadStatusListener?.onAdLoaded(detailMap: detailMap)
    }
    
    public func didTimeoutLoadingSplashAD(withPlacementID placementID: String!) {
        self.splashAdLoadStatusListener?.onAdLoadTimeout()
    }
    
    
    public func splashDidShow(forPlacementID placementID: String!, extra: [AnyHashable : Any]!) {
        self.showingAd = true
        let detailMap = createAdDetailMap(extra: extra)
        self.splashAdLoadStatusListener?.onAdShow(detailMap: detailMap)
    }
    
    public func splashDidClick(forPlacementID placementID: String!, extra: [AnyHashable : Any]!) {
        self.splashAdLoadStatusListener?.onAdClick()
    }
    
    public func splashDidClose(forPlacementID placementID: String!, extra: [AnyHashable : Any]!) {
        self.showingAd = false
        self.splashAdLoadStatusListener?.onAdDismiss()
    }
    
    public func splashDidShowFailed(forPlacementID placementID: String!, error: Error!, extra: [AnyHashable : Any]!) {
        let err = error as NSError
        self.splashAdLoadStatusListener?.onNoAdError(code: String(err.code), desc: err.userInfo[NSLocalizedDescriptionKey] as! String)
    }
    
    public func splashCountdownTime(_ countdown: Int, forPlacementID placementID: String!, extra: [AnyHashable : Any]!) {
        
    }
    
    
    func createAdDetailMap(extra: [AnyHashable : Any]!) -> Dictionary<String, Any> {
        var map = Dictionary<String, Any>()
        if (extra.isEmpty) {
            return map
        }
        map["id"] = extra[kATADDelegateExtraIDKey]
        map["adsource_id"] = extra[kATSplashDelegateExtraAdSourceIDKey]
        map["segment_id"] = extra[kATADDelegateExtraSegmentIDKey]
        map["adsource_price"] = extra[kATSplashDelegateExtraPrice]
        map["adsource_index"] = extra[kATSplashDelegateExtraPriority]
        map["adsource_isheaderbidding"] = extra[kATSplashDelegateExtraAdSourceIsHeaderBidding]
        map["adunit_format"] = extra[kATADDelegateExtraFormatKey]
        map["currency"] = extra[kATADDelegateExtraCurrencyKey]
        map["ecpm_level"] = extra[kATADDelegateExtraECPMLevelKey]
        map["network_firm_id"] = extra[kATSplashDelegateExtraNetworkIDKey]
        map["precision"] = extra[kATADDelegateExtraPrecisionKey]
        map["publisher_revenue"] = extra[kATADDelegateExtraPublisherRevenueKey]
        map["scenario_id"] = extra[kATADDelegateExtraScenarioIDKey]
        map["scenario_reward_name"] = extra[kATADDelegateExtraScenarioRewardNameKey]
        map["scenario_reward_number"] = extra[kATADDelegateExtraScenarioRewardNumberKey]
        map["network_placement_id"] = extra[kATADDelegateExtraNetworkPlacementIDKey]
        return map;
    }
}

